const {ccclass, property} = cc._decorator;

// import TimeUtil from "common/utils/TimeUtil"
import {TimeUtil} from "../../common/index"
import SimulationManager from "../base/lockStep/SimulationManager";
import Simulation from "../base/lockStep/Simulation";
import InputBehaviour from "./behaviour/TestInputBehaviour";
import EntityBehaviour from "../base/lockStep/behaviours/EntityBehaviour";
import MoveSystem from "./system/TestMoveSystem";
import EntityWorld from "../base/ECSR/EntityWorld";
import NotifyMgr from "../base/notify/NotifyMgr";
import {SelfNotification} from "../base/notify/NotifyMgr";
import GameClientData from "./data/TestGameClientData";
import MoveComponent from "./components/TestMoveComponent";
import TransformComponent from "../base/ECSR/components/TransformComponent";


function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
}

@ccclass
export default class Main extends cc.Component {
    @property(cc.Button)
    startBtn:cc.Button = null;
    @property(cc.Button)
    createEntityBtn:cc.Button = null;

    isStart = false;
    world:EntityWorld = null;

    onLoad () {
        this.startBtn.node.on("click", this.StartGame, this);
        this.createEntityBtn.node.on("click", this.createEntity, this);
    }

    StartGame()
    {
        cc.log("Main|StartGame");
        let sim = new Simulation("123");
        this.world = sim.GetEntityWorld();

        let entityBeh = new EntityBehaviour(sim);
        let moveSystem = new MoveSystem(this.world);
        entityBeh.AddSystem(moveSystem);
        cc.log("Main|StartGame|entityBeh length=" + entityBeh.systems.length)
        
        sim.AddBehaviour(new InputBehaviour(sim));
        sim.AddBehaviour(entityBeh);

        cc.log("Main|StartGame|behavirous length=" + sim.behaviours.length)

        SimulationManager.Instance().AddSimulation(sim);
        SimulationManager.Instance().Start();
        this.isStart = true;
    }

    createEntity()
    {
        // NotifyMgr.Instance().Send("", "");
        GameClientData.SelfControlEntityId = guid();
        let entity = this.world.AddEntity(GameClientData.SelfControlEntityId);
        entity.AddComponent(new MoveComponent(15, cc.Vec2.ZERO))
            .AddComponent(new TransformComponent(cc.Vec2.ZERO));
    
        if(entity !== null)
        {
            NotifyMgr.Instance().Send("Entitas.EntityWorld.EntityOperationEvent.CreatePlayer", new SelfNotification("", [entity], this));
        }
    }

    start () {
    }

    update (dt) {
        if(this.isStart)
        {
            SimulationManager.Instance().Run(dt);
        }
    }
}
